//
//  IDataProvider.m
//  Zhidao
//
//  Created by liangqiaozhong on 13-1-11.
//  Copyright (c) 2013年 Baidu.com. All rights reserved.
//

#import "IDataProvider.h"
#import "IManagerBase.h"
#import "Koala.h"
#import "CommonDefines.h"
#import "IDataParser.h"
#import "IDataModel.h"

//#import "BTEngine.h"
#import "JSONKit.h"

#import "TravelException.h"
#import "NSString+NSString_Ex_.h"
//#import "DownloadTaskSceneAreaOffline.h"
//#import "AlbumDBOperator.h"


#import "KFNetwork+request.h"

//#import "LVHotelDataModel.h"
//#import "BaiduTravelAppDelegate.h"


//#define USE_SIMULATION_DATA


#define kMaxMapRequestId2Delegate 1000

#pragma mark -
#pragma mark Url cache policy
@interface IUrlCache : KFUrlDownloadCache 
// Looks at the request's cache policy and any cached headers to determine if the cache data is still valid
- (BOOL)canUseCachedDataForRequest:(ASIHTTPRequest *)request;

-(void)setStoragePath:(NSString *)sp;

@end
@implementation IUrlCache
// Looks at the request's cache policy and any cached headers to determine if the cache data is still valid
- (BOOL)canUseCachedDataForRequest:(ASIHTTPRequest *)request
{
    BOOL canUseCachedData = [super canUseCachedDataForRequest:request];
    //KFLog(@"url %@, use cached data %d",[[request url] absoluteString],canUseCachedData);
    return canUseCachedData;
}

-(void)setStoragePath:(NSString *)sp
{
    [super setStoragePath:sp];
}

@end

#pragma mark -
#pragma mark 内部接口定义
// 单例模式类别
SYNTHESIZE_SINGLETON_FOR_CLASS_PROTOTYPE(IDataProvider)

@interface IDataProvider() 
{
      NSMutableDictionary *_mapRequestId2Delegate;
}


// 映射requestId到IManageDelegate
-(void) mapRequestId2Delegate:(KFRequestParameter *)requestParam
                     delegate:(id<IManagerDelegate>)delegate;

// 删除requestId到IManageDelegate的映射
-(void) removeRequestId2Delegate:(int64_t)requestId;

// 根据requestId获取IManagerDelegate
-(id<IManagerDelegate>) getDelegateFromRequestId:(int64_t)requestId;

// 判断uri对应的本地文件缓存是否存在
-(BOOL) isExistCacheInLocalFile:(NSString *)dataURI;

// 获取uri对应的本地文件缓存
-(NSData*) cacheDataInLocalFile:(NSString *)dataURI;

// 向服务器发起网络请求（传入缓存策略），建立IManagerDelegate和requestId的映射关系
-(id) sendRequest2ServerWithCachePolicy:(NSString *)url
                               delegate:(id<IManagerDelegate>)delegate
                        withCachePolicy:(KFRequestCachePolicy)cachePolicy
                           postDataList:(NSArray*)postDataList
                          postDataValue:(NSDictionary*)postDataValue
                          withUserInfo:(NSDictionary *)requestUserInfo;

// 成功获取网络响应时的处理
-(void)networkDidFinished:(KFNetwork*)aNetwork
             requestParam:(KFRequestParameter*)param
                     data:(id)data;

// 网络响应失败时的处理
-(void)networkDidFailed:(KFNetwork*)aNetwork
           requestParam:(KFRequestParameter*)param
                  error:(NSError*)error;

@end

@implementation IDataProvider

// 单例模式实现
SYNTHESIZE_SINGLETON_FOR_CLASS(IDataProvider)

#pragma mark -
#pragma mark 对象初始化
-(id) init
{
    self = [super init];
    if ( nil == self )
        return self;
    
    // 在此进行初始化定义
    _mapRequestId2Delegate = [[NSMutableDictionary alloc] initWithCapacity:kMaxMapRequestId2Delegate];
    
    NSString *storageCachePath = [[KFNetwork sharedInstance].defaultUrlDownloadCache storagePath];
    
    [KFNetwork sharedInstance].defaultUrlDownloadCache = [ [[IUrlCache alloc] init] autorelease];
    [[KFNetwork sharedInstance].defaultUrlDownloadCache setStoragePath:storageCachePath];
    
    return self;
}

-(void) dealloc
{
    [_mapRequestId2Delegate removeAllObjects];
    kSafeRelease(_mapRequestId2Delegate)

    [super dealloc];
}

#pragma mark -
#pragma mark Network相关操作方法

// 向服务器发起网络请求（传入缓存策略），建立IManagerDelegate和requestId的映射关系
-(id) sendRequest2ServerWithCachePolicy:(NSString *)url
                               delegate:(id<IManagerDelegate>)delegate
                        withCachePolicy:(KFRequestCachePolicy)cachePolicy
                           postDataList:(NSArray*)postDataList
                          postDataValue:(NSDictionary*)postDataValue
                          withUserInfo:(NSDictionary *)requestUserInfo

{
    // 发起网络请求
    KFRequestParameter *param = [KFRequestParameter requestParamWithURL:url];
    param.postValues = postDataValue;
    if ( !param ) 
        return nil;
    param.cachePolicy = cachePolicy;
    param.userInfo = requestUserInfo;
    [KFNetwork sharedInstance].supportCompressedData = YES;
//    NSString *bduss = [AppEngine.loginManager getBDUSS];
    NSString *bduss = nil;
    if (nil != bduss) {
        [KFRequestConfig sharedInstance].tokenToCookie = YES;
        [KFRequestConfig sharedInstance].token = [NSString stringWithFormat:@"BDUSS=%@",bduss];

    }else{
        [KFRequestConfig sharedInstance].tokenToCookie = NO;
        [KFRequestConfig sharedInstance].token = nil;
    }

    NSMutableDictionary *t = [[NSMutableDictionary alloc] initWithObjects:[NSArray arrayWithObject:@"http://223.4.99.93/"] forKeys:[NSArray arrayWithObject:@"Referer"]];
    [KFRequestConfig sharedInstance].httpHeaderData = t;
    [t release];
    
    [[KFNetwork sharedInstance] addRequest:param
                                  delegate:(id<KFNetworkDelegate>)self];
    [[KFNetwork sharedInstance] startReqForParam:param];
    
    // 映射requestId到IManageDelegate
    if (delegate != nil) {
        [self mapRequestId2Delegate:param
                           delegate:delegate];
    }
    
    // 返回param
    return [[param retain] autorelease];
}


// 映射requestId到IManageDelegate
-(void) mapRequestId2Delegate:(KFRequestParameter *)requestParam
                     delegate:(id<IManagerDelegate>)delegate
{
    if ( nil == _mapRequestId2Delegate )
        return;
    
    //chenwh %ld -> %lld
    [_mapRequestId2Delegate safeSetObject:delegate
                                   forKey:[NSString stringWithFormat:@"%lld",requestParam.requestID]];
}


// 删除requestId到IManageDelegate的映射
-(void) removeRequestId2Delegate:(int64_t)requestId
{
    if ( nil == _mapRequestId2Delegate )
        return;
    
    //chenwh %ld -> %lld
    [_mapRequestId2Delegate removeObjectForKey:[NSString stringWithFormat:@"%lld",requestId]];
}

// 根据requestId获取IManagerDelegate
-(id<IManagerDelegate>) getDelegateFromRequestId:(int64_t)requestId
{   
    if ( nil == _mapRequestId2Delegate )
        return nil;
    
    //chenwh %ld -> %lld
    NSString *stringKey = [NSString stringWithFormat:@"%lld",requestId];
    if ( !stringKey ) return nil;
    id<IManagerDelegate> delegate = (id<IManagerDelegate>)[_mapRequestId2Delegate objectForKey:stringKey
                                                                              withDefaultValue:nil];
    return delegate;
}

// 成功获取网络响应时的处理
-(void)networkDidFinished:(KFNetwork*)aNetwork
             requestParam:(KFRequestParameter*)param
                     data:(id)data
{
    // 输入参数判断
    if ( nil == aNetwork || nil == param || nil == data )
        return;
    
    KFLog(@"success data %@",data);
    // 根据requestId获取IManagerDelegate
    id<IManagerDelegate> delegate = [self getDelegateFromRequestId:param.requestID];
    if ( nil == delegate )
        return;
    
    // 解析数据模型
    IDataModel *dataModel = [[IDataParser sharedInstance] parseDataFromJSON:data
                                                           withRequestParam:param];
    if ( nil == dataModel )
    {
        // 数据获取失败，调用IManagerDelegate更新UI
        if ( delegate && [delegate respondsToSelector:@selector(updateViewForError:withRequestId:)] )
        {
            [delegate updateViewForError:[[[NSError alloc] init] autorelease]
                           withRequestId:param.requestID];
        }
        else if ( delegate && [delegate respondsToSelector:@selector(updateViewForError:withRequestParam:)] )
        {
            [delegate updateViewForError:[[[NSError alloc] init] autorelease]
                        withRequestParam:param];
        }
        return;
    }
    
    // 根据param的userInfo设置离线包标识isDataFromOfflinePackage
    NSString *offlineName = [param.userInfo stringValueForKey:@"isDataFromOfflinePackage" defaultValue:nil operation:NSStringOperationTypeTrim];
    dataModel.isDataFromOfflinePackage = (nil == offlineName)?NO:YES;
    dataModel.userInfo = param.userInfo;
    
    // 根据param的userInfo设置(dbkey不为空，且不是从数据库中获取的json)写数据库字段将json数据库持久化到本地DB  chenjiedan
    NSString *loadFromDBCached = [param.userInfo stringValueForKey:@"LoadFromDBJsonCache" defaultValue:nil operation:NSStringOperationTypeTrim];
    
    dataModel.jsonValue = [data JSONString];
    if ([dataModel.jsonValue length] < 4) {
        dataModel.jsonValue = nil;
    }
    if (nil == loadFromDBCached) {
        dataModel.isDataFromDB = NO;
        NSString *dbKey = [param.userInfo stringValueForKey:@"DBKey" defaultValue:nil operation:NSStringOperationTypeTrim];
        if (dbKey != nil && ![dbKey isEqualToString:@""]) {
            dataModel.dbKey = dbKey;
            if ([dataModel respondsToSelector:@selector(saveInDB)]) {
                [dataModel saveInDB];
            }
        }
    }else{
        dataModel.isDataFromDB = YES;
    }

   
    // 数据模型解析成功，调用IManagerDelegate更新UI
    
//    NSRange range = [[dataModel description] rangeOfString:@"errno = 0"];
//    BOOL error = NO;
//    if (range.location == NSNotFound) {
//        error = YES;
//    }
    
    if (delegate && [delegate respondsToSelector:@selector(updateViewForSuccess:withRequestId:)] )
    {
        [delegate updateViewForSuccess:dataModel
                         withRequestId:param.requestID];
    }
    else if ( delegate && [delegate respondsToSelector:@selector(updateViewForSuccess:withRequestParam:)] )
    {
        [delegate updateViewForSuccess:dataModel
                      withRequestParam:param];
    }
}

// 网络响应失败时的处理
-(void)networkDidFailed:(KFNetwork*)aNetwork
           requestParam:(KFRequestParameter*)param
                  error:(NSError*)error
{
    // 输入参数判断
    if ( nil == aNetwork || nil == param )
        return;
    
    // 根据requestId获取IManagerDelegate
    id<IManagerDelegate> delegate = [self getDelegateFromRequestId:param.requestID];
    if ( nil == delegate )
        return;
    
    // 网络数据获取失败，调用IManagerDelegate更新UI
    if ( delegate && [delegate respondsToSelector:@selector(updateViewForError:withRequestId:)] )
    {
        [delegate updateViewForError:error
                       withRequestId:param.requestID];
    }
    else if ( delegate && [delegate respondsToSelector:@selector(updateViewForError:withRequestParam:)] )
    {
        [delegate updateViewForError:error
                    withRequestParam:param];
    }
}

#pragma mark -
#pragma mark 数据处理接口

// 判断uri对应的本地文件缓存是否存在
-(BOOL) isExistCacheInLocalFile:(NSString *)dataURI
{
    KFUrlDownloadCache *urlCache = (KFUrlDownloadCache *)[KFNetwork sharedInstance].defaultUrlDownloadCache;
    NSString  *cachePath = [urlCache pathToCachedResponseDataForURL:[NSURL URLWithString:dataURI]];
    return  ( nil != cachePath );
}

// 获取uri对应的本地文件缓存
-(NSData*) cacheDataInLocalFile:(NSString *)dataURI
{
    KFUrlDownloadCache *urlCache = (KFUrlDownloadCache *)[KFNetwork sharedInstance].defaultUrlDownloadCache;
    NSData  *cacheData = [urlCache cachedResponseDataForURL:[NSURL URLWithString:dataURI]];
    return  cacheData;
}

// 获取数据
-(id) syncFetchData:(NSString *)dataURI
{
    return nil;
}

// 异步获取数据，返回请求Id
-(int64_t) asyncFetchData:(NSString *)dataURI
          withCachePolicy:(IDataCachePolicy)cachePolicy
       withDataParseClass:(Class)parseClass
         withDataDelegate:(id<IManagerDelegate>)delegate
{
    return [self asyncFetchDataWithUserInfo:dataURI
                                   userInfo:nil
                            withCachePolicy:cachePolicy
                         withDataParseClass:parseClass
                           withDataDelegate:delegate];
}

//- (NSString *)fileNameWithTagName:(NSString *)tagName
//                      withTagList:(NSArray*)tag_list
//                     withPathList:(NSArray*)path_list
//{
//    if ([NSString stringIsNullOrEmpty:tagName])
//    {
//        return nil;
//    }
//    
//    //判断tag_list存在否
//    NSString *fileName = nil;
//    //    NSString *filePath = nil;
//    
//    NSUInteger index = [tag_list indexOfObject:tagName];
//    
//    if (NSNotFound != index && index < [path_list count])
//    {
//        //存在
//        
//        fileName = [path_list objectAtIndex:index withDefaultValue:nil];
//    }
//    
//    if ([tagName isEqualToString:SceneTagTopScene]
//        || [tagName isEqualToString:SceneTagLocalScene])
//    {
//        //周边景点，离线的时候 需要热门景点，但是这时候，以这个逻辑是找不到的，所以，添加一个约定的查找
//        fileName = SceneTagTopScene;
//    }
//    
//    return fileName;
//}

- (void)parseTagListWithData:(NSDictionary*)data
           withReturnTaglist:(NSMutableArray*)tag_list
          withReturnPathList:(NSMutableArray*)path_list
{
    //解析TagList
    NSArray *tagNameArray = [data arrayValueForKey:@"tag_list" defaultValue:nil];
    
    if (tagNameArray != nil && [tagNameArray isKindOfClass:[NSArray class]])
    {
        NSMutableArray *mArr = [NSMutableArray arrayWithCapacity:[tagNameArray count]];
        NSMutableArray *mArrPath = [NSMutableArray arrayWithCapacity:[tagNameArray count]];
        
        for (int i = 0; i < [tagNameArray count]; i++)
        {
            if ([[tagNameArray objectAtIndex:i withDefaultValue:nil] isKindOfClass:[NSDictionary class]])
            {
                if ([[tagNameArray objectAtIndex:i withDefaultValue:nil] objectForKey:@"tag" withDefaultValue:nil])
                {
                    [mArr addObject:[[[tagNameArray objectAtIndex:i withDefaultValue:nil] objectForKey:@"tag" withDefaultValue:nil] description] withDefaultValue:nil];
                    
                    if ([[tagNameArray objectAtIndex:i] objectForKey:@"path" withDefaultValue:nil])
                    {
                        [mArrPath addObject:[[[tagNameArray objectAtIndex:i withDefaultValue:nil] objectForKey:@"path" withDefaultValue:nil] description] withDefaultValue:nil];
                    }
                    else
                    {
                        //路径要是没有，就放tag
                        [mArrPath addObject:[[[tagNameArray objectAtIndex:i withDefaultValue:nil] objectForKey:@"tag" withDefaultValue:nil] description] withDefaultValue:nil];
                    }
                }
            }
            else
            {
                [mArr addObjectsFromArray:tagNameArray];
                break;
            }
        }
        
        [tag_list removeAllObjects];
        [tag_list addObjectsFromArray:mArr];
        [path_list removeAllObjects];
        [path_list addObjectsFromArray:mArrPath];
    }
}

//- (NSString*)filePathWithTagName:(NSString*)tagName
//                     withTagList:(NSArray*)tag_list
//                    withPathList:(NSArray*)path_list
//                     withSceneId:(NSString*)sid
//            withOfflineParentSid:(NSString*)offlineParentSid
//{
//    if ([NSString stringIsNullOrEmpty:tagName])
//    {
//        return nil;
//    }
//    
//    //判断tag_list存在否
//    NSString *filePath = nil;
//    
//    NSUInteger index = [tag_list indexOfObject:tagName];
//    
//    if (NSNotFound != index && index < [path_list count])
//    {
//        //存在
//        
//        NSString *parentSid = offlineParentSid;
//        
//        filePath = [DownloadTaskSceneAreaOffline destStoragePath:parentSid];
//        
//        if (![parentSid isEqualToString:sid])
//        {
//            //说明是子景点
//            filePath = [filePath stringByAppendingPathComponent:parentSid];
//        }
//        
//        filePath = [filePath stringByAppendingPathComponent:sid];
//        filePath = [filePath stringByAppendingPathComponent:[self fileNameWithTagName:tagName withTagList:tag_list
//                                                                         withPathList:path_list]];
//    }
//    
//    if ([tagName isEqualToString:SceneTagTopScene]
//        || [tagName isEqualToString:SceneTagLocalScene])
//    {
//        //周边景点，离线的时候 需要热门景点，但是这时候，以这个逻辑是找不到的，所以，添加一个约定的查找
//        
//        filePath = [DownloadTaskSceneAreaOffline destStoragePath:offlineParentSid];
//        filePath = [filePath stringByAppendingPathComponent:offlineParentSid];
//        filePath = [filePath stringByAppendingPathComponent:[self fileNameWithTagName:tagName
//                                                                          withTagList:tag_list
//                                                                         withPathList:path_list]];
//    }
//    
//    return filePath;
//}

#pragma mark - 解析旧版本
//- (id)getOldVersionDataWithUserInfo:(NSDictionary*)userInfoT
//{
//    NSMutableDictionary* dict4All = [NSMutableDictionary dictionaryWithCapacity:1];
//
//    NSString* offlinePath = nil;
//        
//    NSMutableDictionary* userInfo = [NSMutableDictionary dictionaryWithDictionary:userInfoT];
//    
//    NSString* tagName = [userInfo stringValueForKey:@"TagName"
//                                       defaultValue:nil
//                                          operation:NSStringOperationTypeTrim];
//    
//    [userInfo setObject:@"index" forKey:@"OfflineName" withDefaultValue:nil];
//    
//    if (![BTEngine isExistOfflineDataWithUserInfo:userInfo WithOfflinePath:&offlinePath])
//    {
//        return dict4All;
//    }
//    
//    NSData* jsonDataTemp = [[[NSData alloc] initWithContentsOfFile:offlinePath] autorelease];
//    
//    JSONDecoder* dc = [JSONDecoder decoder];
//    NSError* err = nil;
//    NSDictionary* dataTemp = (NSDictionary*)[dc objectWithData:jsonDataTemp error:&err];
//    
//    if ([dataTemp isKindOfClass:[NSDictionary class]])
//    {
//        dataTemp = [dataTemp dictionaryValueForKey:@"data"
//                                      defaultValue:nil];
//        
//        if ([tagName isEqualToString:@"shopping"])
//        {
//            //购物的解析方式
//            NSDictionary* dict4AllTemp = [self parseOldVersion4ShoppingWithData:dataTemp];
//            dict4All = [NSMutableDictionary dictionaryWithDictionary:dict4AllTemp?dict4AllTemp:[NSDictionary dictionary]];
//        }
//        else if([tagName isEqualToString:@"dining"])
//        {
//            //美食的解析方式
//            NSDictionary* dict4AllTemp = [self parseOldVersion4DiningWithData:dataTemp];
//            dict4All = [NSMutableDictionary dictionaryWithDictionary:dict4AllTemp?dict4AllTemp:[NSDictionary dictionary]];
//        }
//        else if([tagName isEqualToString:@"accommodation"])
//        {
//            //住宿的解析方式
//            NSDictionary* dict4AllTemp = [self parseOldVersion4AccommodationWithData:dataTemp];
//            dict4All = [NSMutableDictionary dictionaryWithDictionary:dict4AllTemp?dict4AllTemp:[NSDictionary dictionary]];
//        }
//        else if ([tagName isEqualToString:@"abstract"] || [tagName isEqualToString:@"abs"])
//        {
//            //城市简介的解析方式
//            NSDictionary* dict4AllTemp = [self parseOldVersion4AbstractWithData:dataTemp];
//            dict4All = [NSMutableDictionary dictionaryWithDictionary:dict4AllTemp?dict4AllTemp:[NSDictionary dictionary]];
//        }
//        else if ([tagName isEqualToString:@"attention"] || [tagName isEqualToString:@"useful"] || [tagName isEqualToString:@"leave_info"] || [tagName isEqualToString:@"geography_history"] || [tagName isEqualToString:@"new_geography_history"] || [tagName isEqualToString:@"entertainment"])
//        {
//            if ([tagName isEqualToString:@"new_geography_history"])
//            {
//                tagName = @"geography_history";
//            }
//            
//            NSDictionary* dict4AllTemp = [self parseOldVersion4UsefulInfoWithData:dataTemp TagName:tagName];
//            dict4All = [NSMutableDictionary dictionaryWithDictionary:dict4AllTemp?dict4AllTemp:[NSDictionary dictionary]];
//        }
//        else if([tagName isEqualToString:@"traffic"])
//        {
//            //交通的解析方式，特殊，因为之前是一级界面
//            NSDictionary* dict4AllTemp = [self parseOldVersion4TrafficWithData:dataTemp];
//            dict4All = [NSMutableDictionary dictionaryWithDictionary:dict4AllTemp?dict4AllTemp:[NSDictionary dictionary]];
//        }
//        else if([tagName isEqualToString:@"new_line"])
//        {
//            //路线的解析方式
//            NSDictionary* dict4AllTemp = [self parseOldVersion4NewLineWithData:dataTemp];
//            dict4All = [NSMutableDictionary dictionaryWithDictionary:dict4AllTemp?dict4AllTemp:[NSDictionary dictionary]];
//        }
//    }
//    
//    return dict4All;
//}

- (id)parseOldVersion4ShoppingWithData:(NSDictionary*)dataTemp
{
    NSDictionary* dictTemp = [dataTemp dictionaryValueForKey:@"shopping"
                                                defaultValue:nil];
    
    NSString* desc = [dictTemp stringValueForKey:@"desc"
                                    defaultValue:@""
                                       operation:NSStringOperationTypeTrim];
    NSArray* tabs = [dictTemp arrayValueForKey:@"tabs"
                                  defaultValue:nil];
    
    NSMutableArray* businessArr = [NSMutableArray arrayWithCapacity:3];
    NSMutableArray* goodsArr = [NSMutableArray arrayWithCapacity:1];
    NSMutableArray* articlesArr = [NSMutableArray arrayWithCapacity:1];
    
    for (NSDictionary* dict4Tab in tabs)
    {
        //旧版的很悲剧，里头有个type来区分
        NSString* type = [dict4Tab stringValueForKey:@"type"
                                        defaultValue:nil
                                           operation:NSStringOperationTypeTrim];
        
        if ([type isEqualToString:@"business"])
        {
            [businessArr addObject:dict4Tab withDefaultValue:nil];
        }
        else if ([type isEqualToString:@"goods"])
        {
            [goodsArr addObject:dict4Tab withDefaultValue:nil];
        }
        else if ([type isEqualToString:@"article"])
        {
            [articlesArr addObject:dict4Tab withDefaultValue:nil];
        }
    }
    
    //组织
    //1.组织business
    NSDictionary* data4All = [NSDictionary dictionaryWithObject:[NSDictionary dictionaryWithObjectsAndKeys:desc?desc:@"",@"desc",businessArr,@"business",
                                                                 goodsArr,@"goods",
                                                                 articlesArr,@"article",nil] forKey:@"data"];
    return data4All;
}

- (id)parseOldVersion4DiningWithData:(NSDictionary*)dataTemp
{
    NSDictionary* dictTemp = [dataTemp dictionaryValueForKey:@"dining"
                                                defaultValue:nil];
    
    NSString* desc = [dictTemp stringValueForKey:@"desc"
                                    defaultValue:@""
                                       operation:NSStringOperationTypeTrim];
    NSArray* tabs = [dictTemp arrayValueForKey:@"tabs"
                                  defaultValue:nil];
    
    NSMutableArray* foodArr = [NSMutableArray arrayWithCapacity:3];
    NSMutableArray* placeArr = [NSMutableArray arrayWithCapacity:1];
    NSMutableArray* storesArr = [NSMutableArray arrayWithCapacity:1];
    
    for (NSDictionary* dict4Tab in tabs)
    {
        //旧版的很悲剧，里头有个type来区分
        NSString* type = [dict4Tab stringValueForKey:@"type"
                                        defaultValue:nil
                                           operation:NSStringOperationTypeTrim];
        
        if ([type isEqualToString:@"food"])
        {
            [foodArr addObject:dict4Tab withDefaultValue:nil];
        }
        else if ([type isEqualToString:@"place"])
        {
            [placeArr addObject:dict4Tab withDefaultValue:nil];
        }
        else if ([type isEqualToString:@"stores"])
        {
            [storesArr addObject:dict4Tab withDefaultValue:nil];
        }
    }
    
    //组织
    NSDictionary* data4All = [NSDictionary dictionaryWithObject:[NSDictionary dictionaryWithObjectsAndKeys:desc?desc:@"",@"desc",foodArr,@"food",
                                                                 placeArr,@"place",
                                                                 storesArr,@"stores",nil] forKey:@"data"];
    return data4All;
}

- (id)parseOldVersion4AccommodationWithData:(NSDictionary*)dataTemp
{
    NSDictionary* dictTemp = [dataTemp dictionaryValueForKey:@"accommodation"
                                                defaultValue:nil];
    
    NSString* desc = [dictTemp stringValueForKey:@"desc"
                                    defaultValue:@""
                                       operation:NSStringOperationTypeTrim];
    NSArray* tabs = [dictTemp arrayValueForKey:@"tabs"
                                  defaultValue:nil];
    
    NSMutableArray* whereArr = [NSMutableArray arrayWithCapacity:3];
    NSMutableArray* articleArr = [NSMutableArray arrayWithCapacity:1];
    
    for (NSDictionary* dict4Tab in tabs)
    {
        //旧版的很悲剧，里头有个type来区分
        NSString* type = [dict4Tab stringValueForKey:@"type"
                                        defaultValue:nil
                                           operation:NSStringOperationTypeTrim];
        
        if ([type isEqualToString:@"where"])
        {
            [whereArr addObject:dict4Tab withDefaultValue:nil];
        }
        else if ([type isEqualToString:@"article"])
        {
            [articleArr addObject:dict4Tab withDefaultValue:nil];
        }
    }
    
    //组织
    NSDictionary* data4All = [NSDictionary dictionaryWithObject:[NSDictionary dictionaryWithObjectsAndKeys:desc?desc:@"",@"desc",articleArr,@"article",
                                                                 whereArr,@"where",nil] forKey:@"data"];
    return data4All;
}

//返回最老的离线包中的城市简介数据
-(id)parseOldVersion4AbstractWithData:(NSDictionary*)dataTemp{
    NSDictionary* dictTemp = [dataTemp dictionaryValueForKey:@"abstract"
                                                defaultValue:nil];
    
    return dictTemp;
}

//返回最老的离线包中的实用信息相关数据
-(id)parseOldVersion4UsefulInfoWithData:(NSDictionary*)dataTemp TagName:(NSString *)tagName{
    NSDictionary* dictTemp = [dataTemp dictionaryValueForKey:tagName
                                                defaultValue:nil];
    NSString* desc = [dictTemp stringValueForKey:@"desc"
                                    defaultValue:@""
                                       operation:NSStringOperationTypeTrim];
    NSString *sid = [dictTemp stringValueForKey:@"sid" defaultValue:@"" operation:NSStringOperationTypeTrim];
    NSString *sname = [dictTemp stringValueForKey:@"sname" defaultValue:@"" operation:NSStringOperationTypeTrim];
    
    NSArray* tabs = [dictTemp arrayValueForKey:@"tabs"
                                  defaultValue:nil];
    
    
    //组织
    NSDictionary* data4All = [NSDictionary dictionaryWithObject:[NSDictionary dictionaryWithObjectsAndKeys:desc?desc:@"",@"desc",sid?sid:@"",@"sid",sname?sname:@"",@"sname",
                                                                 tabs,@"list",nil] forKey:@"data"];
    return data4All;
}


- (id)parseOldVersion4NewLineWithData:(NSDictionary*)dataTemp
{
    NSDictionary* dictTemp = [dataTemp dictionaryValueForKey:@"new_line"
                                                defaultValue:nil];
    
    NSString* desc = [dictTemp stringValueForKey:@"desc"
                                         defaultValue:@""
                                            operation:NSStringOperationTypeTrim];
    NSArray* tabs = [dictTemp arrayValueForKey:@"tabs"
                                  defaultValue:[NSArray array]];
    
    //组织
    NSDictionary* data4All = [NSDictionary dictionaryWithObject:[NSDictionary dictionaryWithObjectsAndKeys:desc?desc:@"",@"desc",tabs,@"list",nil]
                                                         forKey:@"data"];
    return data4All;
}

//- (id)parseOldVersion4TrafficWithData:(NSDictionary*)dataTemp
//{
//    //特殊，交通之前是一级界面
//    
//    //先解析local
//    NSDictionary* dictTemp = [dataTemp dictionaryValueForKey:@"local"
//                                                defaultValue:nil];
//    
//    NSString* localDesc = [dictTemp stringValueForKey:@"desc"
//                                         defaultValue:@""
//                                            operation:NSStringOperationTypeTrim];
//    NSArray* tabs = [dictTemp arrayValueForKey:@"tabs"
//                                  defaultValue:nil];
//    
//    NSMutableArray* localArr = [NSMutableArray arrayWithCapacity:3];
//    NSMutableArray* remoteArr = [NSMutableArray arrayWithCapacity:1];
//    
//    for (NSDictionary* dict4Tab in tabs)
//    {
//        [localArr addObject:dict4Tab withDefaultValue:nil];
//    }
//    
//    dictTemp = [dataTemp dictionaryValueForKey:@"remote"
//                                  defaultValue:nil];
//    
//    NSString* remoteDesc = [dictTemp stringValueForKey:@"desc"
//                                          defaultValue:@""
//                                             operation:NSStringOperationTypeTrim];
//    tabs = [dictTemp arrayValueForKey:@"tabs"
//                         defaultValue:nil];
//    
//    for (NSDictionary* dict4Tab in tabs)
//    {
//        [remoteArr addObject:dict4Tab withDefaultValue:nil];
//    }
//    
//    //组织
//    NSDictionary* data4All = [NSDictionary dictionaryWithObject:[NSDictionary dictionaryWithObjectsAndKeys:localDesc?localDesc:@"",@"desc",localArr,@"local",
//                                                                 remoteArr,@"remote",nil] forKey:@"data"];
//    return data4All;
//}

#pragma mark -

//- (id)getTagListPathDataWithUserInfo:(NSDictionary*)userInfo
//{
//    NSMutableDictionary* dict4All = [NSMutableDictionary dictionaryWithCapacity:1];
//
//    NSString* tagName = [userInfo stringValueForKey:@"TagListTag"
//                                       defaultValue:nil
//                                          operation:NSStringOperationTypeTrim];
//    NSString* tagFileName = [userInfo stringValueForKey:@"OfflineName"
//                                           defaultValue:nil
//                                              operation:NSStringOperationTypeTrim];
//    NSString* sid = [userInfo stringValueForKey:@"SceneId"
//                                   defaultValue:nil
//                                      operation:NSStringOperationTypeTrim];
//    NSString* parentSid = [userInfo stringValueForKey:@"ParentSid"
//                                         defaultValue:nil
//                                            operation:NSStringOperationTypeTrim];
//    NSString* desc = nil;
//    
//    if (![NSString stringIsNullOrEmpty:tagName]
//        && ![NSString stringIsNullOrEmpty:tagFileName])
//    {
//        //说明含有下级tag_list
//        NSData* jsonDataTemp = nil;
//        NSString* filePathTemp = [self filePathWithTagName:tagName
//                                               withTagList:[NSArray arrayWithObject:tagName]
//                                              withPathList:[NSArray arrayWithObject:tagFileName]
//                                               withSceneId:sid
//                                      withOfflineParentSid:parentSid];
//        
//        if ([[NSFileManager defaultManager] fileExistsAtPath:filePathTemp])
//        {
//            jsonDataTemp = [[[NSData alloc] initWithContentsOfFile:filePathTemp] autorelease];
//            
//            JSONDecoder* dc = [JSONDecoder decoder];
//            NSError* err = nil;
//            id dataTemp = [dc objectWithData:jsonDataTemp error:&err];
//            
//            NSDictionary* dictDataTemp = (NSDictionary*)dataTemp;
//            
//            if ([dictDataTemp isKindOfClass:[NSDictionary class]])
//            {
//                dictDataTemp = [dictDataTemp dictionaryValueForKey:@"data"
//                                                      defaultValue:nil];
//                desc = [dictDataTemp stringValueForKey:@"desc"
//                                          defaultValue:nil
//                                             operation:NSStringOperationTypeTrim];
//                NSMutableArray* tag_list = [NSMutableArray arrayWithCapacity:3];
//                NSMutableArray* path_list = [NSMutableArray arrayWithCapacity:3];
//                
//                [self parseTagListWithData:dictDataTemp
//                         withReturnTaglist:tag_list
//                        withReturnPathList:path_list];
//                
//                NSMutableArray* arr4All = [NSMutableArray arrayWithCapacity:3];
//                //解析所有tag_list中子文件
//                for (NSString* tagNameTemp in tag_list)
//                {
//                    NSString* tagFilePathTemp = [self filePathWithTagName:tagNameTemp
//                                                              withTagList:tag_list
//                                                             withPathList:path_list
//                                                              withSceneId:sid
//                                                     withOfflineParentSid:parentSid];
//                    
//                    if ([[NSFileManager defaultManager] fileExistsAtPath:tagFilePathTemp])
//                    {
//                        jsonDataTemp = [[[NSData alloc] initWithContentsOfFile:tagFilePathTemp] autorelease];
//                        
//                        dataTemp = [dc objectWithData:jsonDataTemp
//                                                error:&err];
//                        
//                        dictDataTemp = (NSDictionary*)dataTemp;
//                        
//                        if ([dictDataTemp isKindOfClass:[NSDictionary class]])
//                        {
//                            NSArray* arrListTemp = [dictDataTemp arrayValueForKey:@"data"
//                                                                     defaultValue:nil];
//                            
//                            if (!arrListTemp)
//                            {
//                                arrListTemp = [[dictDataTemp dictionaryValueForKey:@"data"
//                                                                     defaultValue:nil] arrayValueForKey:@"tabs"
//                                               defaultValue:nil];
//                            }
//                            
//                            if (!arrListTemp)
//                            {
//                                arrListTemp = [[dictDataTemp dictionaryValueForKey:@"data"
//                                                                      defaultValue:nil] arrayValueForKey:@"list"
//                                               defaultValue:nil];
//                            }
//                            
//                            if (!arrListTemp)
//                            {
//                                arrListTemp = [[dictDataTemp dictionaryValueForKey:@"data"
//                                                                      defaultValue:nil] arrayValueForKey:@"lists"
//                                               defaultValue:nil];
//                            }
//                            
//                            if (arrListTemp)
//                            {
//                                [arr4All addObject:[NSDictionary dictionaryWithObject:arrListTemp
//                                                                               forKey:tagNameTemp] withDefaultValue:nil];
//                            }
//                        }
//                    }
//                }
//                
//                NSMutableDictionary* dict4Objects = [NSMutableDictionary dictionaryWithCapacity:3];
//                
//                for (NSDictionary* obj in arr4All)
//                {
//                    [dict4Objects addEntriesFromDictionary:obj];
//                }
//                
//                if (![NSString stringIsNullOrEmpty:desc])
//                {
//                    [dict4Objects setObject:desc forKey:@"desc"];
//                }
//                
//                [dict4All setObject:dict4Objects forKey:@"data"];
//            }
//        }
//    }
//    
//    return dict4All;
//}

// 异步获取数据，返回请求Id（附加以Dictionary方式传递用户参数）
/*userInfo 的格式为一个字典，至少包括以下的数据
 *QueryType:查询的内容类型为枚举型：ERequestType，主要是（RequestTypeSceneDetail，RequestTypeNotesView，RequestTypeNoteData，RequestTypeSceneData
 *SceneId：景点的id
 *ParentSid：景点的父节点的id
 *NoteId：游记的id
 *OfflineName：离线文件的标识
 *TagListTag:tag_list的tag（有该字段，说明还有二级，需要再次解析一个中间文件的tag_list）
 *TagName:tagName
 *IsOffline
 *--------------optional
 *FakeJson 
 *DBKey
 *LoadFromDBJsonCache
 *PostDataValue
 */

- (int64_t)asyncFetchDataWithUserInfo:(NSString *)dataURI
                             userInfo:(NSDictionary *)userInfo
                      withCachePolicy:(IDataCachePolicy)cachePolicy
                   withDataParseClass:(Class)parseClass
                     withDataDelegate:(id<IManagerDelegate>)delegate
{

//#ifdef USE_SIMULATION_DATA    
//    //Add By Chenjiedan For FakeJson Construct
    NSString *jsonPath = [userInfo objectForKey:@"FakeJson" withDefaultValue:nil];
    if (jsonPath != nil) {
        return [self asyncFetchLocalFakeDataWithUserInfo:jsonPath userInfo:userInfo withCachePolicy:cachePolicy withDataParseClass:parseClass withDataDelegate:delegate];
    }
//#endif
    
#ifdef USE_SIMULATION_DATA
    {
        // 分配KFRequestParameter
        KFRequestParameter *offlineParam = [[KFRequestParameter new]autorelease];
        if (nil == offlineParam)
        {
            return kInvalidRequestId;
        }
        
        // 生成requestid
        offlineParam.requestID = [[KFNetwork sharedInstance]addRequestCount];
        
        // 设置param的userinfo,以便在networkDidFinished里设置数据模型的离线包标识：isDataFromOfflinePackage
        offlineParam.userInfo = userInfo;
        
        // 映射requestId到IManageDelegate
        [self mapRequestId2Delegate:offlineParam delegate:delegate];
        
        // 将请求参数映射到数据模型类，以便网络响应完成后进行数据模型解析
        [[IDataParser sharedInstance] mapRequestParam2DataModelClass:offlineParam andDataModelClass:parseClass];
        
        dispatch_async(dispatch_get_main_queue(), ^{
            [self networkDidFinished:[KFNetwork sharedInstance] requestParam:offlineParam data:[NSDictionary dictionary]];
        });

        return offlineParam.requestID;
    }
#endif
    
    // 输入参数判断
    if ( nil == dataURI )
        return kInvalidRequestId;
    
    // 根据传入参数设置缓存策略
    KFRequestCachePolicy requestCachePolicy = NetWorkUesCachePolicyAndFailBackToLoadCacheData;
    switch (cachePolicy) {
        case IDataCachePolicyLocalFile:
        {
            requestCachePolicy = NetWorkOnlyLoadDataFromCachePolicy;
            break;
        }
        case IDataCachePolicyLocalFileAndNetwork:
        {
            requestCachePolicy = NetWorkUesCachePolicyAndFailBackToLoadCacheData;
            break;
        }
        case IDataCachePolicyNetwork:
        {
            requestCachePolicy = NetWorkRequestDontUseCachePolicy;
            break;
        }
//        case IDataCachePolicyOfflinePackageAndFileAndNetwork:
//        {
//            if ( nil == userInfo ) {
//                requestCachePolicy = NetWorkUesCachePolicyAndFailBackToLoadCacheData;
//                break;
//            }
//        
////            BOOL isOffline = [[userInfo objectForKey:@"IsOffline" withDefaultValue:[NSNumber numberWithBool:NO]] boolValue];
//            
//            //判断是否是二级list，如dining
//            BOOL needParseTagList = ([userInfo objectForKey:@"TagListTag" withDefaultValue:nil] != nil ? YES:NO);
//            
//            NSDictionary* dict4All = needParseTagList ? [self getTagListPathDataWithUserInfo:userInfo]:nil;
//            
//            // 判断是否存在离线下载包，如果否，则break，并赋值requestCachePolicy＝NetWorkUesCachePolicyAndFailBackToLoadCacheData
//            
//            NSString *offlinePath = nil;
//            
//            BOOL hasLocalArticle = NO;
//            
//            NSString* tagName = [userInfo objectForKey:@"TagName" withDefaultValue:nil];
//            NSString* offlineName = [userInfo objectForKey:@"OfflineName" withDefaultValue:nil];
//            
//            if ([tagName isEqualToString:@"article"] && offlineName)
//            {
//                offlinePath = [[[[DownloadTaskSceneAreaOffline destStoragePath:[BTEngine getParentSid]] stringByAppendingPathComponent:[BTEngine getParentSid]] stringByAppendingPathComponent:@"article"] stringByAppendingPathComponent:offlineName];
//                
//                if ([[NSFileManager defaultManager] fileExistsAtPath:offlinePath])
//                {
//                    hasLocalArticle = YES;
//                }
//            }
//            
//            if (!hasLocalArticle && ![BTEngine isExistOfflineDataWithUserInfo:userInfo WithOfflinePath:&offlinePath]) {
//                
//                //找不到子文件等，说明是旧的数据包
//                if (userInfo)
//                {
//                    //在这里对index文件进行解析，解析完，拼接成新的格式，赋值给dict4All
//                    dict4All = [self getOldVersionDataWithUserInfo:userInfo];
//                    if ([dict4All count] == 0) {
//                        requestCachePolicy = NetWorkUesCachePolicyAndFailBackToLoadCacheData;
//                        break;
//                    }
//                }
//                else
//                {
//                    requestCachePolicy = NetWorkUesCachePolicyAndFailBackToLoadCacheData;
//                    break;
//                }
//            }
//            
//            BOOL hasAlreadyParsed = ([dict4All count] > 0 ? YES:NO);
//            
//            // 分配KFRequestParameter
//            KFRequestParameter *offlineParam = [[KFRequestParameter new]autorelease];
//            if (nil == offlineParam)
//            {
//                return kInvalidRequestId;
//            }
//            
//            // 生成requestid
//            offlineParam.requestID = [[KFNetwork sharedInstance]addRequestCount];
//            
//            // 设置param的userinfo,以便在networkDidFinished里设置数据模型的离线包标识：isDataFromOfflinePackage
//            NSMutableDictionary* offlineUserInfo = [NSMutableDictionary dictionaryWithDictionary:userInfo];
//            [offlineUserInfo setValue:@"isDataFromOfflinePackage" forKey:@"isDataFromOfflinePackage"];
//            offlineParam.userInfo = offlineUserInfo;
//            
//            // 映射requestId到IManageDelegate
//            [self mapRequestId2Delegate:offlineParam delegate:delegate];
//            
//            // 将请求参数映射到数据模型类，以便网络响应完成后进行数据模型解析
//            if (parseClass != nil) {
//                [[IDataParser sharedInstance] mapRequestParam2DataModelClass:offlineParam
//                                                           andDataModelClass:parseClass];
//            }
//
//            
//            if (!needParseTagList)
//            {
//                // 根据传入url参数，找到离线json文件，并读取json内容
//                NSData *jsonData = nil;
//                if (offlinePath && !hasAlreadyParsed)
//                {
//                    //找到路径了。
//                    jsonData = [[[NSData alloc]initWithContentsOfFile:offlinePath] autorelease];
//                }
//                // 调用networkDidFinished，并传入json内容和delegate
//                if ((nil == jsonData || 0 == jsonData.length)&&!hasAlreadyParsed)
//                {
//                    //当json文件为空或者没有这个文件，回调失败
//                    dispatch_async(dispatch_get_main_queue(), ^{
//                        [self networkDidFailed:[KFNetwork sharedInstance] requestParam:offlineParam error:nil];
//                    });
//                }
//                else
//                {
//                    JSONDecoder* dc = [JSONDecoder decoder];
//                    NSError* err = nil;
//                    id data = nil;
//                    
//                    if (!hasAlreadyParsed)
//                    {
//                        data = [dc objectWithData:jsonData error:&err];
//                    }
//                    else
//                    {
//                        data = dict4All;
//                    }
//                    
//                    if(err != nil)
//                    {
//                        
//                        NSDictionary* dict = [NSDictionary dictionaryWithObject:@"successCallBack, DICT，json parse Error Not a JSON" forKey:@"errorMessage" ];
//                        KFLog(@"successCallBack, DICT，json parse Error Not a JSON");
//                        
//                        NSError* error = [NSError errorWithDomain:@"_KFrameWork_Core_network"
//                                                             code:10002
//                                                         userInfo:dict];
//                        dispatch_async(dispatch_get_main_queue(), ^{
//                            [self networkDidFailed:[KFNetwork sharedInstance] requestParam:offlineParam error:error];
//                        });
//                    }
//                    
//                    dispatch_async(dispatch_get_main_queue(), ^{
//                        [self networkDidFinished:[KFNetwork sharedInstance] requestParam:offlineParam data:data];
//                    });
//                }
//                
//                return offlineParam.requestID;
//                // 返回requestid
//            }
//            else
//            {
//                if (hasAlreadyParsed)
//                {
//                    dispatch_async(dispatch_get_main_queue(), ^{
//                        [self networkDidFinished:[KFNetwork sharedInstance] requestParam:offlineParam data:dict4All];
//                    });
//                }
//                else
//                {
////                    if (!isOffline)
//                    {//在线，本地没有找到，则联网
//                        requestCachePolicy = NetWorkUesCachePolicyAndFailBackToLoadCacheData;
//                        break;
//                    }
//                    
//                    NSDictionary* dict = [NSDictionary dictionaryWithObject:@"successCallBack, DICT，json parse Error Not a JSON" forKey:@"errorMessage" ];
//                    KFLog(@"successCallBack, DICT，json parse Error Not a JSON");
//                    NSError* error = [NSError errorWithDomain:@"_KFrameWork_Core_network"
//                                                         code:10002
//                                                     userInfo:dict];
//                    dispatch_async(dispatch_get_main_queue(), ^{
//                        [self networkDidFailed:[KFNetwork sharedInstance] requestParam:offlineParam error:error];
//                    });
//                }
//                
//                return offlineParam.requestID;
//            }
//        }
//        case IDataCachePolicyDBCachedJson:
//        {
//            NSString *dbKey = [userInfo objectForKey:@"DBKey" withDefaultValue:nil];
//            //从本地数据库中查找，尝试找到已经存储的json数据。
//            NSString *dbJson =  [self jsonInDBForKey:dbKey];
//            //判断是否找到json数据
//             return   [self fetchLocalCachedJson:dbJson WithUserInfo:userInfo withCachePolicy:IDataCachePolicyDBCachedJson withDataParseClass:parseClass withDataDelegate:delegate];
//      
//        }
    }
    
    // 发起网络请求
    
    NSDictionary *DIC = [userInfo objectForKey:@"PostDataValue" withDefaultValue:nil];
    
    KFRequestParameter *param = (KFRequestParameter *)
    [self sendRequest2ServerWithCachePolicy:dataURI
                                   delegate:delegate
                            withCachePolicy:requestCachePolicy
                               postDataList:nil
                              postDataValue:DIC
                                   withUserInfo:userInfo];
    
    //如果userInfo中带有DBKey字段，说明需要存储此JSON数据
    NSString *dbKey = [userInfo objectForKey:@"DBKey" withDefaultValue:nil];
    if (nil != dbKey) {
        param.userInfo = userInfo;
    }

    
    if ( nil == param )
        return kInvalidRequestId;
    
    // 将请求参数映射到数据模型类，以便网络响应完成后进行数据模型解析
    if (parseClass != nil) {
        [[IDataParser sharedInstance] mapRequestParam2DataModelClass:param
                                                   andDataModelClass:parseClass];
    }
    
    // 返回请求Id
    return param.requestID;
}

// 异步Post数据，返回请求Id
-(int64_t) asyncPostData:(NSString *)dataURI
              postValues:(NSDictionary *)postVaues
            postDataList:(NSArray *)dataArrays
//         withCachePolicy:(IDataCachePolicy)cachePolicy
                userInfo:(NSDictionary *)userInfo
      withDataParseClass:(Class)parseClass
        withDataDelegate:(id<IManagerDelegate>)delegate
{
    
    NSString *jsonPath = [userInfo objectForKey:@"FakeJson" withDefaultValue:nil];
    if (jsonPath != nil) {
        return [self asyncFetchLocalFakeDataWithUserInfo:jsonPath userInfo:userInfo withCachePolicy:IDataCachePolicyLocalFileAndNetwork withDataParseClass:parseClass withDataDelegate:delegate];
    }
    
    // 输入参数判断
    if ( nil == dataURI ) 
        return kInvalidRequestId;
    
    // 发起网络请求
    KFRequestParameter *param = [KFRequestParameter requestParamWithURL:dataURI
                                                             postValues:postVaues
                                                           postDataList:dataArrays
                                                                 method:@"POST"];
    if ( !param ) 
        return kInvalidRequestId;
    
    //如果userInfo中带有DBKey字段，说明需要存储此JSON数据
    NSString *dbKey = [userInfo objectForKey:@"DBKey" withDefaultValue:nil];
    if (nil != dbKey) {
        param.userInfo = userInfo;
    }

    
    param.cachePolicy = NetWorkRequestDontUseCachePolicy;
//    NSString *bduss = [AppEngine.loginManager getBDUSS];
    NSString *bduss = nil;
    if (nil != bduss) {
        [KFRequestConfig sharedInstance].tokenToCookie = YES;
        [KFRequestConfig sharedInstance].token = [NSString stringWithFormat:@"BDUSS=%@",bduss];
    }else{
        [KFRequestConfig sharedInstance].tokenToCookie = NO;
        [KFRequestConfig sharedInstance].token = nil;
    }
    [[KFNetwork sharedInstance] addRequest:param delegate:(id<KFNetworkDelegate>)self];
    [[KFNetwork sharedInstance] startReqForParam:param];
    
    // 映射requestId到IManageDelegate
    [self mapRequestId2Delegate:param delegate:(id<IManagerDelegate>)delegate];
    
    // 将请求参数映射到数据模型类，以便网络响应完成后进行数据模型解析
    if (parseClass != nil) {
        [[IDataParser sharedInstance] mapRequestParam2DataModelClass:param
                                                   andDataModelClass:parseClass];
    }
    
    // 返回请求Id
    return param.requestID;

}
// 保存数据
-(BOOL) saveData:(NSString *)dataURI
            data:(id)data
{
    return NO;
}


// 取消数据获取(或数据Post)请求（传入请求Id）
-(void) cancelFetchDataRequestByRequestID:(int64_t)requestId
{
    if ( kInvalidRequestId == requestId )
        return;
    
    [self removeRequestId2Delegate:requestId];
    
    [[KFNetwork sharedInstance] cancelForReqId:requestId];
}

#pragma mark
#pragma mark 用于测试：获取本地假JSON数据

- (int64_t)asyncFetchLocalFakeDataWithUserInfo:(NSString *)jsonPath
                             userInfo:(NSDictionary *)userInfo
                      withCachePolicy:(IDataCachePolicy)cachePolicy
                   withDataParseClass:(Class)parseClass
                     withDataDelegate:(id<IManagerDelegate>)delegate
{
    // 分配KFRequestParameter
    KFRequestParameter *param = [[KFRequestParameter new]autorelease];
    if (nil == param)
    {
        return kInvalidRequestId;
    }
    
    // 生成requestid
    param.requestID = [[KFNetwork sharedInstance]addRequestCount];
    
    // 设置param的userinfo,以便在networkDidFinished里设置数据模型的离线包标识：isDataFromOfflinePackage
    param.userInfo = userInfo;
    
    // 映射requestId到IManageDelegate
    [self mapRequestId2Delegate:param delegate:delegate];
    
    // 将请求参数映射到数据模型类，以便网络响应完成后进行数据模型解析
    [[IDataParser sharedInstance] mapRequestParam2DataModelClass:param andDataModelClass:parseClass];
    
    [self parseLocalJson:jsonPath withRequstParameter:param];
    
    return param.requestID;
}
-(void) parseLocalJson:(NSString*)offlinePath withRequstParameter:(KFRequestParameter*)param
{
    // 根据传入url参数，找到离线json文件，并读取json内容
    NSData *jsonData = nil;
    
    //找到路径了。
    offlinePath = [[NSBundle mainBundle] pathForResource:offlinePath ofType:nil];

    jsonData = [[[NSData alloc]initWithContentsOfFile:offlinePath] autorelease];
    
    // 调用networkDidFinished，并传入json内容和delegate
    if ((nil == jsonData || 0 == jsonData.length))
    {
        //当json文件为空或者没有这个文件，回调失败
        dispatch_async(dispatch_get_main_queue(), ^{
            [self networkDidFailed:[KFNetwork sharedInstance] requestParam:param error:nil];
        });
    }
    else
    {
        JSONDecoder* dc = [JSONDecoder decoder];
        NSError* err = nil;
        id data = nil;
        
        data = [dc objectWithData:jsonData error:&err];

        if(err != nil)
        {
            NSDictionary* dict = [NSDictionary dictionaryWithObject:@"successCallBack, DICT，json parse Error Not a JSON" forKey:@"errorMessage" ];
            KFLog(@"successCallBack, DICT，json parse Error Not a JSON");
            
            NSError* error = [NSError errorWithDomain:@"_KFrameWork_Core_network"
                                                 code:10002
                                             userInfo:dict];
            dispatch_async(dispatch_get_main_queue(), ^{
                [self networkDidFailed:[KFNetwork sharedInstance] requestParam:param error:error];
            });
        }
        dispatch_async(dispatch_get_main_queue(), ^{
            [self networkDidFinished:[KFNetwork sharedInstance] requestParam:param data:data];
        });
    }
}


#pragma mark
#pragma mark 查找本地DB数据库
//-(NSString *)jsonInDBForKey:(NSString *)dbKey
//{
//    if ([dbKey isEqualToString:@""] || nil == dbKey) {
//        return nil;
//    }else{
//        return   [[AlbumDBOperator sharedInstance] loadAlbumListWithKey:dbKey];
//    }
//}



//-(int64_t) fetchLocalCachedJson:(NSString *)localJson
//                   WithUserInfo:(NSDictionary *)userInfo
//                withCachePolicy:(IDataCachePolicy)cachePolicy
//             withDataParseClass:(Class)parseClass
//               withDataDelegate:(id<IManagerDelegate>)delegate
//{
//    // 分配KFRequestParameter
//    KFRequestParameter *offlineParam = [[KFRequestParameter new]autorelease];
//    if (nil == offlineParam)
//    {
//        return kInvalidRequestId;
//    }
//    
//    // 生成requestid
//    offlineParam.requestID = [[KFNetwork sharedInstance]addRequestCount];
//
//    // 设置param的userinfo,以便在networkDidFinished里设置数据模型的离线包标识：isDataFromOfflinePackage
//    NSMutableDictionary *mutDic = [NSMutableDictionary dictionaryWithDictionary:userInfo];
//    [mutDic setObject:@"YES" forKey:@"LoadFromDBJsonCache"];
//    offlineParam.userInfo = mutDic;
//    
//    // 映射requestId到IManageDelegate
//    [self mapRequestId2Delegate:offlineParam delegate:delegate];
//    
//    // 将请求参数映射到数据模型类，以便网络响应完成后进行数据模型解析
//    if (parseClass != nil) {
//        [[IDataParser sharedInstance] mapRequestParam2DataModelClass:offlineParam
//                                                   andDataModelClass:parseClass];
//    }
//    // 调用networkDidFinished，并传入json内容和delegate
//    if ((nil == localJson || 0 == localJson.length))
//    {
//        //当json文件为空或者没有这个文件，回调失败
//        dispatch_async(dispatch_get_main_queue(), ^{
//            [self networkDidFinished:[KFNetwork sharedInstance] requestParam:offlineParam data:[NSDictionary dictionary]];
////            [self networkDidFailed:[KFNetwork sharedInstance] requestParam:offlineParam error:nil];
//        });
//    }
//    else
//    {
//        JSONDecoder* dc = [JSONDecoder decoder];
//        NSError* err = nil;
//        id data = nil;
//        NSData *jsonData = [localJson dataUsingEncoding:NSUTF8StringEncoding];
//
//       
//        data = [dc objectWithData:jsonData error:&err];
//       
//        
//        if(err != nil)
//        {
//            
//            NSDictionary* dict = [NSDictionary dictionaryWithObject:@"successCallBack, DICT，json parse Error Not a JSON" forKey:@"errorMessage" ];
//            KFLog(@"successCallBack, DICT，json parse Error Not a JSON");
//            
//            NSError* error = [NSError errorWithDomain:@"_KFrameWork_Core_network"
//                                                 code:10002
//                                             userInfo:dict];
//            dispatch_async(dispatch_get_main_queue(), ^{
//                [self networkDidFailed:[KFNetwork sharedInstance] requestParam:offlineParam error:error];
//            });
//        }
//        
//        dispatch_async(dispatch_get_main_queue(), ^{
//            [self networkDidFinished:[KFNetwork sharedInstance] requestParam:offlineParam data:data];
//        });
//    }
//    return offlineParam.requestID;
//}
@end
